﻿using ApprovalFlow_WebApi.PlugIn;
using Infrastructure.Repository.overallAuth;
using Model;
using Model.OverallAtuhModel;
using System.ComponentModel;
using System.Reflection;
using Utility;

namespace CoreDomain
{
    /// <summary>
    /// 数据列核心
    /// </summary>
    public class DataColsCore
    {
        /// <summary>
        /// 通过反射同步数据列
        /// </summary>
        public static ReceiveStatus SynchronousCols(LoginOutPut loginOutPut)
        {
            ReceiveStatus receiveStatus = new ReceiveStatus();
            //反射
            Assembly assembly = Assembly.Load("Model");
            List<Type> types = assembly.GetTypes().Where(p => p.FullName.Contains("OutPut")).ToList<Type>();
            var currentAssembly = Assembly.LoadFrom(assembly.Location);
            var geoEntityTypes = currentAssembly.ExportedTypes.Where(p => p.FullName.StartsWith("Model.BusinessModel.OutPut")).ToList();

            var config = AppSettingsPlugIn.GetNode<OpenApiConfig>("OpenApiConfig");

            //进行便利获取的所有的程序集中的类
            foreach (var geoEntityType in geoEntityTypes)
            {
                var property = geoEntityType.GetProperties();
                var i = 0;
                var dateTime = DateTime.Now;

                //取类上的自定义特性
                var menuId = string.Empty;
                object[] objs = geoEntityType.GetCustomAttributes(typeof(EnitityMappingAttribute), true);
                foreach (object obj in objs)
                {
                    EnitityMappingAttribute? attr = obj as EnitityMappingAttribute;
                    if (attr != null)
                    {
                        menuId = attr.MenuId;//菜单id
                        break;
                    }
                }

                if (!string.IsNullOrWhiteSpace(menuId))
                {
                    foreach (var item in property)
                    {
                        //描述/注释 属性上
                        DescriptionAttribute? descriptionAttribute = item.GetCustomAttribute(typeof(DescriptionAttribute)) as DescriptionAttribute;
                        if (descriptionAttribute == null)
                            continue;
                        string propertyDescription = descriptionAttribute?.Description ?? item.Name; // 如果没有描述/注释，则使用属性名作为默认值

                        var fieldName = item.Name;

                        SysMenuTableCols sysMenuTableCols = new SysMenuTableCols()
                        {
                            FieldId = Guid.NewGuid().ToString(),
                            MenuId = menuId,
                            FieldEnName = fieldName,
                            CorporationKey = loginOutPut.CorporationKey,
                            SystemKey = loginOutPut.SystemKey,
                            FieldType = item.PropertyType.Name,
                            FieldCnName = propertyDescription,
                            FieldOrderBy = i++,
                            FieldWidth = 100,
                            FieldFixed = string.Empty,
                            FieldSortable = false,
                            FieldAlign = "left",
                            CreateTime = dateTime,
                            CreateUser = "6A75EC49-2093-4B89-950F-65E6E72746BA",
                            IsDisplay = true,
                        };
                        try
                        {
                            string url = string.Format("api/SysMenuTableCols/GetTableColsByMenuIdOrFieldName?menuId={0}&fieldEnName={1}", menuId, fieldName);
                            //post请求
                            var data = HttpRequest.GetAsync<List<SysMenuTableCols>>(url).Result;

                            //没有就新增，有就修改
                            if (data.Data == null && data.Success)
                            {
                                var result = HttpRequest.PostAsync<string>("api/SysMenuTableCols/InsertCols", sysMenuTableCols, loginOutPut.Token).Result;
                            }
                            else if (data.Data != null && data.Success)
                            {
                                data.Data[0].FieldEnName = fieldName;
                                data.Data[0].FieldType = item.PropertyType.Name;
                                var result = HttpRequest.PostAsync<string>("api/SysMenuTableCols/UpdateTableCols", data.Data[0], loginOutPut.Token).Result;
                            }
                        }
                        catch (Exception ex)
                        {
                            receiveStatus.success = false;
                            receiveStatus.code = Utility.Enum.CodeStatuEnum.Error;
                            receiveStatus.msg = ex.Message;
                            ExceptionHelper.CustomException(ex.Message);
                            break;
                        }
                    }
                }
            }
            return receiveStatus;
        }
    }
}
